
package com.test.tree;

import java.util.ArrayList;
import java.util.List;

public class BinaryTree {
	private int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
	private static List<Node> nodes = null;
	
	private static class Node{
		Node leftChild;
		Node rightChild;
		int data;
		Node(int data){
			this.data = data;
			this.leftChild = null;
			this.rightChild = null;
		}
	}
	
	private void createBinaryTree(){
		nodes = new ArrayList<Node>();
		for(int num : array){
			nodes.add(new Node(num));
		}
		for(int i=0; i<nodes.size()/2 - 1; i++){
			nodes.get(i).leftChild = nodes.get(i * 2 + 1);
			nodes.get(i).rightChild = nodes.get(i * 2 + 2);
		}
		nodes.get(nodes.size() / 2).leftChild = nodes.get((nodes.size() - 1) / 2 * 2 + 1);
		if(nodes.size() % 2 != 0){
			nodes.get(nodes.size() / 2).rightChild = nodes.get(nodes.size() - 1);
		}
		for(Node n : nodes){
			System.out.print(n.data + ", ");
		}
	}
	
	private void preorderTraversal(Node node){
		if(node == null){
			return;
		}
		System.out.print(node.data + ", ");
		preorderTraversal(node.leftChild);
		preorderTraversal(node.rightChild);
	}
	
	private void inorderTraversal(Node node){
		if(node == null){
			return;
		}
		inorderTraversal(node.leftChild);
		System.out.print(node.data + ", ");
		inorderTraversal(node.rightChild);
	}
	
	private void postorderTraversal(Node node){
		if(node == null){
			return;
		}
		postorderTraversal(node.leftChild);
		postorderTraversal(node.rightChild);
		System.out.print(node.data + ", ");
	}
	
	public static void main(String[] args) {
		BinaryTree bt = new BinaryTree();
		System.out.println("初始化二叉树：");
		bt.createBinaryTree();
		
		System.out.println("\n先序遍历：");
		bt.preorderTraversal(bt.nodes.get(0)); 
		
		System.out.println("\n中序遍历：");
		bt.inorderTraversal(bt.nodes.get(0));
		
		System.out.println("\n后序遍历：");
		bt.postorderTraversal(bt.nodes.get(0));
	}
}
